""" 
@coding  : utf-8
@Time    : 2023/4/14 17:15
@Author  : Rumou
@File    : 猜拳.py
@Description: 好，一直在修bug
"""
import json
import random
import time


# 用户可以创建房间，加入房间
# 加入房间后，房间要两个人才能开始游戏，按任意键开始游戏
# 两个人互相猜拳，两个人随机出剪刀石头布，输的人扣100金豆
# 直到金豆为0或q退出

# 房间类
# 属性：房间ID，房间内用户
# 用户类
# 属性：用户ID，用户余额，用户所在房间

def load_users():
    """读取用户信息"""
    try:
        with open('users.json', 'r', encoding='utf-8') as f:
            users = json.load(f)
    except (FileNotFoundError, json.JSONDecodeError):
        users = {}
    return users


def save_users(users):
    """保存用户信息"""
    with open('users.json', 'w', encoding='utf-8') as f:
        json.dump(users, f, ensure_ascii=False, indent=1)


def load_rooms():
    """读取房间信息"""
    try:
        with open('rooms.json', 'r', encoding='utf-8') as f:
            rooms = json.load(f)
    except (FileNotFoundError, json.JSONDecodeError):
        rooms = {}
    return rooms


def save_rooms(rooms):
    """保存房间信息"""
    with open('rooms.json', 'w', encoding='utf-8') as f:
        json.dump(rooms, f, ensure_ascii=False, indent=1)


class User:
    def __init__(self, username):
        """新建用户"""
        self.username = username
        self.money = 1000
        self.locate_room = "0"

    def move(self, moved_in_room_id):
        """移动"""
        users_info = load_users()
        rooms_info = load_rooms()
        name = self.username
        if moved_in_room_id not in rooms_info:
            print("房间ID不存在")
            return
        user_located_room = self.locate_room  # 获取用户原来所在房间ID
        if user_located_room != "0":  # 如果用户已进入房间
            rooms_info[user_located_room]["usernames"].remove(name)  # 将用户从原来所在房间删除
        self.locate_room = moved_in_room_id  # 更改用户当前所在房间ID
        rooms_info[moved_in_room_id]["usernames"].append(name)  # 增加房间内玩家名
        save_users(users_info)
        save_rooms(rooms_info)
        print(f"用户 {name} 已移至房间 {moved_in_room_id} ")


class Room:
    def __init__(self, room_id):
        """初始化房间"""
        self.room_id = room_id
        self.usernames = []

    def show_room(self):
        """查看房间信息"""
        print(f"房间ID:{self.room_id}")
        print("房间内玩家:", end='')
        for i in self.usernames:
            print(i, end=',')

    def play_game(self):
        load_users()
        print("开始游戏".center(20, "*"))
        user1, user2 = self.usernames

        # 随机生成石头剪刀布
        hands = ["石头", "剪刀", "布"]
        random.seed(time.time())
        hand1 = random.choice(hands)
        hand2 = random.choice(hands)
        print(f"{user1}: {hand1}")
        print(f"{user2}: {hand2}")

        if hand1 == hand2:
            print("平局")
        elif hand1 == "石头" and hand2 == "剪刀" \
                or hand1 == "布" and hand2 == "石头" \
                or hand1 == "剪刀" and hand2 == "布":
            print(f"{user1} 获胜")
            return 1
        else:
            print(f"{user2} 获胜")
            return 2
        return


def main():
    print("欢迎来到猜拳游戏".center(20, "*"))
    while True:
        print("游戏菜单".center(20, "*"))
        menu_choice = input(
            "1.用户管理\n2.房间管理\n3.进行游戏\n4.退出游戏\n请输入选择：")
        if menu_choice == "1":
            while True:
                print("用户管理".center(20, "*"))
                user_manager_choice = input(
                    "1.新建用户\n2.删除用户\n3.查询用户列表\n4.修改用户余额\n5.退出用户管理\n请输入:")
                if user_manager_choice == "1":  # 新建用户
                    users_info = load_users()
                    username = input("请输入要新建的用户名:")
                    if username in users_info:
                        print("用户名已存在")
                    else:
                        user = User(username)
                        users_info[user.username] = {"money": user.money, "locate_room": user.locate_room}
                        save_users(users_info)
                        print(f"用户 {user.username} 创建成功")
                elif user_manager_choice == "2":  # 删除用户
                    users_info = load_users()
                    username = input("请输入要删除的用户名:")
                    if username not in users_info:
                        print("用户名不存在")
                    else:
                        user = User(username)
                        del users_info[user.username]
                        save_users(users_info)
                        print(f"用户 {user.username} 删除成功")
                elif user_manager_choice == "3":  # 查询用户列表
                    users_info = load_users()
                    if not users_info:  # 用户列表为空
                        print("用户列表为空")
                    else:
                        print("序号\t用户名\t\t用户余额\t\t用户所在房间")
                        for i, username in enumerate(users_info, 1):
                            if users_info[username]['locate_room'] == "0":
                                print(f"{i:02d}\t{username:<10}\t{users_info[username]['money']:<10}"
                                      f"\t用户没有加入房间")
                            else:
                                print(f"{i:02d}\t{username:<10}\t{users_info[username]['money']:<10}"
                                      f"\t{users_info[username]['locate_room']:<10}")
                elif user_manager_choice == "4":  # 修改用户余额
                    users_info = load_users()
                    username = input("请输入要修改余额的用户名:")
                    if username not in users_info:
                        print("用户名不存在")
                    else:
                        money = input("请输入修改后的余额:")
                        if money.isdigit():
                            users_info[username]['money'] = money
                            print(f"修改成功！用户 {username} 当前余额为 {money}")
                        else:
                            print("输入有误")
                    save_users(users_info)
                elif user_manager_choice == "5":  # 退出用户管理
                    print("退出用户管理")
                    break
                else:
                    print("输入有误")
        elif menu_choice == "2":  # 房间管理
            while True:
                print("房间管理".center(20, "*"))
                room_manager_choice = input(
                    "1.新建房间\n2.删除房间\n3.查询房间列表\n4.移动玩家\n5.退出房间管理\n请输入:")
                if room_manager_choice == "1":  # 新建房间
                    rooms_info = load_rooms()
                    room_id = input("请输入要新建的房间ID:")
                    if room_id in rooms_info:
                        print("房间ID已存在")
                    else:
                        room = Room(room_id)
                        rooms_info[room.room_id] = {}
                        save_rooms(rooms_info)
                        print(f"房间 {room.room_id} 创建成功")
                elif room_manager_choice == "2":  # 删除房间
                    rooms_info = load_rooms()
                    room_id = input("请输入要删除的房间ID:")
                    if room_id not in rooms_info:
                        print("房间ID不存在")
                    else:
                        room = Room(room_id)
                        del rooms_info[room.room_id]
                        save_rooms(rooms_info)
                        print(f"房间 {room.room_id} 删除成功")
                elif room_manager_choice == "3":  # 查询房间列表
                    rooms_info = load_rooms()
                    if not rooms_info:  # 房间列表为空
                        print("房间列表为空")
                    else:
                        print("房间ID\t玩家1\t\t玩家2")
                        for room_id, room_info in rooms_info.items():
                            usernames = room_info["usernames"]
                            player1 = usernames[0] if len(usernames) >= 1 else "无"
                            player2 = usernames[1] if len(usernames) >= 2 else "无"
                            print(f"{room_id:2s}\t\t{player1:6s}\t\t{player2:6s}")
                elif room_manager_choice == "4":  # 移动玩家
                    users_info = load_users()
                    rooms_info = load_rooms()
                    moved_username = input("请输入想要移动的用户名:")
                    moved_in_room_id = input("请输入想要移动到的房间ID:")
                    if moved_username not in users_info:
                        print("用户名不存在")
                        continue
                    if moved_in_room_id not in rooms_info:
                        print("房间ID不存在")
                        continue
                    if len(rooms_info[moved_in_room_id]["usernames"]) == 2:
                        print(rooms_info[moved_in_room_id]["usernames"])
                        print(len(rooms_info[moved_in_room_id]["usernames"]))
                        print("房间已满")
                        continue
                    moved_user = User(moved_username)
                    moved_user.locate_room = users_info[moved_username]["locate_room"]
                    moved_user.move(moved_in_room_id)
                elif room_manager_choice == "5":  # 退出房间管理
                    print("退出用户管理")
                    break
                else:
                    print("输入有误")
        elif menu_choice == "3":  # 开始游戏
            rooms_info = load_rooms()
            users_info = load_users()
            print("游戏准备".center(20, "*"))
            room_choiced_id = input("请输入要开始游戏的房间ID:")
            if room_choiced_id not in rooms_info:
                print("房间ID不存在")
            else:
                if len(rooms_info[room_choiced_id]['usernames']) != 2:
                    print("房间人数不足2人，无法开始游戏")
                    continue
                room_choiced = Room(room_choiced_id)
                for name in users_info:
                    if users_info[name]["locate_room"] == room_choiced.room_id:
                        room_choiced.usernames.append(name)
                user1, user2 = room_choiced.usernames
                user1_money = users_info[user1]["money"]
                user2_money = users_info[user2]["money"]
                while True:
                    play_input = input("按下任意键开始游戏。输入'q'退出:")
                    if play_input == 'q':
                        break
                    else:
                        if user1_money < 100:
                            print(f"{user1} 余额不足，游戏中止")
                            break
                        if user2_money < 100:
                            print(f"{user2} 余额不足，游戏中止")
                            break
                        if room_choiced.play_game() == 1:  # 用户1赢
                            user1_money += 100
                            user2_money -= 100
                        elif room_choiced.play_game() == 2:  # 用户2赢
                            user1_money -= 100
                            user2_money += 100
                        else:
                            pass
                        users_info[user1]["money"] = user1_money
                        users_info[user2]["money"] = user2_money
                        save_users(users_info)
        elif menu_choice == "4":  # 退出游戏
            print("退出游戏")
            break
        else:
            print("输入有误")


# 执行主程序
if __name__ == "__main__":
    main()
